'use client';

import { useEffect, useState } from 'react';
import { Table, message, Button, Modal, Form, Input, Tag, Spin } from 'antd';
import { useUser } from '../../context/userContext';
import api from '../../utils/api';
import styles from '@/components/Font.module.css';

export default function PostManagementPage() {
    const { user } = useUser();
    const accessToken = user? user.access_token : "";
    const [categories, setCategories] = useState([]);
    const [createCategoryModalVisible, setCreateCategoryModalVisible] = useState(false);
    const [updateCategoryModalVisible, setUpdateCategoryModalVisible] = useState(false);
    const [selectedCategory, setSelectedCategory] = useState(null);
    const [loading, setLoading] = useState(false);
    // 创建表单实例
    const [createCategoryForm] = Form.useForm();
    const [updateCategoryForm] = Form.useForm();

    const fetchCategories = async () => {
        setLoading(true);
        try {
            const response = await api.get('/categories/all', {
                headers: { Authorization: `Bearer ${accessToken}` }
            });
            if (!response.data ||!Array.isArray(response.data.Reponse)) {
                console.error('分区数据格式错误，Reponse 不是数组:', response.data);
                throw new Error('分区数据格式错误，Reponse 不是数组');
            }
            setCategories(response.data.Reponse);
        } catch (error) {
            console.log(error, '获取分区信息失败');
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        fetchCategories();
    }, []);

    const handleCreateCategory = async (values) => {
        try {
            const requestData = {
                id: parseInt(values.id),
                name: values.name,
                description: values.description
            };
            console.log('创建分区请求数据:', requestData);
            const response = await api.post('/categories/create', requestData, {
                headers: {
                    Authorization: `Bearer ${accessToken}`,
                    'Content-Type': 'application/json'
                }
            });
            console.log('创建分区响应数据:', response.data);
            if (response.status === 201) {
                message.success('分区创建成功！');
                setCreateCategoryModalVisible(false);
                await fetchCategories();
            }
        } catch (error) {
            console.log(error, '创建分区出错');
        }
    };

    const handleUpdateCategory = async (values) => {
        try {
            const requestData = {
                id: selectedCategory.id,
                name: values.name,
                description: values.description
            };
            const response = await api.put('/categories/update', requestData, {
                headers: {
                    Authorization: `Bearer ${accessToken}`,
                    'Content-Type': 'application/json'
                }
            });
            if (response.status === 200) {
                message.success('分区更新成功！');
                setUpdateCategoryModalVisible(false);
                await fetchCategories();
            }
        } catch (error) {
            console.log(error, '更新分区出错');
        }
    };

    const handleDeleteCategory = async (categoryId) => {
        try {
            const response = await api.delete(`/categories/delete?id=${categoryId}`, {
                headers: {
                    Authorization: `Bearer ${accessToken}`
                }
            });
            if (response.status === 200) {
                message.success('分区删除成功！');
                await fetchCategories();
            }
        } catch (error) {
            console.log(error, '删除分区出错');
        }
    };
    
    const categoryColumns = [
        { 
            title: 'ID', 
            dataIndex: 'id', 
            key: 'id',
            className: styles.text,
            width: 80,
        },
        { 
            title: '名称', 
            dataIndex: 'name', 
            key: 'name',
            className: styles.text,
            width: 150,
        },
        { 
            title: '描述', 
            dataIndex: 'description', 
            key: 'description',
            className: styles.text,
            width: 300,
        },
        {
            title: '操作',
            key: 'action',
            className: styles.text,
            width: 220,
            render: (_, record) => (
                <div className="flex space-x-2">
                    <Button 
                        type="primary" 
                        className="bg-[#D6A7A1] hover:bg-[#E8D6D0] text-white rounded-md transition-all text-sm px-3 py-1.5"
                        onClick={() => {
                            setSelectedCategory(record);
                            updateCategoryForm.setFieldsValue({
                                name: record.name,
                                description: record.description
                            });
                            setUpdateCategoryModalVisible(true);
                        }}
                    >
                        更新
                    </Button>
                    <Button 
                        type="primary" 
                        danger 
                        className="bg-[#A3989D] hover:bg-[#C1B7B0] text-white rounded-md transition-all text-sm px-3 py-1.5"
                        onClick={() => handleDeleteCategory(record.id)}
                    >
                        删除
                    </Button>
                </div>
            )
        }
    ];

  return (
    <div className="bg-[#F4EDEB] rounded-2xl shadow-md p-6">
        <h2 className={`${styles.titlesmall} text-xl mb-6 text-[#7A6E6E]`}>分区管理</h2>
        
        <Button 
            type="primary" 
            className="bg-[#D6A7A1] hover:bg-[#E8D6D0] text-white rounded-md transition-all text-sm px-4 py-2 mb-6"
            onClick={() => setCreateCategoryModalVisible(true)}
        >
            创建分区
        </Button>
        
        {/* 表格容器 - 固定表头，内容可滚动 */}
        <div className="overflow-hidden bg-white rounded-xl shadow-sm h-[calc(100vh-200px)]">
            <Spin spinning={loading}>
                <Table
                    columns={categoryColumns}
                    dataSource={categories}
                    pagination={false}
                    className="bordered={false}"
                    rowClassName={(record, index) => index % 2 === 0 ? 'bg-white' : 'bg-[#F4EDEB]/50'}
                    size="middle"
                    scroll={{ y: "calc(100vh - 200px)" }} // 增加表格高度，展示更多内容
                    components={{
                        header: {
                            cell: ({ className, ...restProps }) => (
                                <th
                                    {...restProps}
                                    className={`${className} ${styles.titlesmall} text-base font-semibold text-[#7A6E6E] bg-[#F4EDEB] sticky top-0 z-10`}
                                />
                            ),
                        },
                    }}
                />
            </Spin>
        </div>
        
        {/* 创建分区模态框 */}
        <Modal
            title={<span className={`${styles.titlesmall} text-base font-semibold text-[#7A6E6E]`}>创建分区</span>}
            visible={createCategoryModalVisible}
            onOk={() => {
                createCategoryForm.validateFields().then((values) => {
                    handleCreateCategory(values);
                }).catch((errorInfo) => {
                    console.log('表单验证失败:', errorInfo);
                });
            }}
            onCancel={() => setCreateCategoryModalVisible(false)}
            className="rounded-xl overflow-hidden bg-[#F4EDEB]"
            style={{ borderRadius: '16px' }}
            footer={[
                <Button 
                    key="cancel" 
                    className="bg-[#A3989D] hover:bg-[#C1B7B0] text-white rounded-md transition-all text-sm px-3 py-1.5"
                    onClick={() => setCreateCategoryModalVisible(false)}
                >
                    取消
                </Button>,
                <Button 
                    key="ok" 
                    type="primary"
                    className="bg-[#D6A7A1] hover:bg-[#E8D6D0] text-white rounded-md transition-all text-sm px-3 py-1.5"
                    onClick={() => {
                        createCategoryForm.validateFields().then((values) => {
                            handleCreateCategory(values);
                        }).catch((errorInfo) => {
                            console.log('表单验证失败:', errorInfo);
                        });
                    }}
                >
                    创建
                </Button>,
            ]}
        >
            <div className="p-4 bg-white rounded-lg shadow-sm">
                <Form form={createCategoryForm} layout="vertical">
                    <Form.Item
                        label={<span className={`${styles.text} font-medium text-gray-700`}>分区ID</span>}
                        name="id"
                        rules={[{ required: true, message: '请输入分区ID' }]}
                    >
                        <Input className="rounded-md border-gray-300 focus:border-[#D6A7A1] focus:ring focus:ring-[#D6A7A1]/20 transition-all" />
                    </Form.Item>
                    <Form.Item
                        label={<span className={`${styles.text} font-medium text-gray-700`}>分区名称</span>}
                        name="name"
                        rules={[{ required: true, message: '请输入分区名称' }]}
                    >
                        <Input className="rounded-md border-gray-300 focus:border-[#D6A7A1] focus:ring focus:ring-[#D6A7A1]/20 transition-all" />
                    </Form.Item>
                    <Form.Item
                        label={<span className={`${styles.text} font-medium text-gray-700`}>分区描述</span>}
                        name="description"
                    >
                        <Input className="rounded-md border-gray-300 focus:border-[#D6A7A1] focus:ring focus:ring-[#D6A7A1]/20 transition-all" />
                    </Form.Item>
                </Form>
            </div>
        </Modal>
        
        {/* 更新分区模态框 */}
        <Modal
            title={<span className={`${styles.titlesmall} text-base font-semibold text-[#7A6E6E]`}>更新分区</span>}
            visible={updateCategoryModalVisible}
            onOk={() => {
                updateCategoryForm.validateFields().then((values) => {
                    handleUpdateCategory(values);
                }).catch((errorInfo) => {
                    console.log('表单验证失败:', errorInfo);
                });
            }}
            onCancel={() => setUpdateCategoryModalVisible(false)}
            className="rounded-xl overflow-hidden bg-[#F4EDEB]"
            style={{ borderRadius: '16px' }}
            footer={[
                <Button 
                    key="cancel" 
                    className="bg-[#A3989D] hover:bg-[#C1B7B0] text-white rounded-md transition-all text-sm px-3 py-1.5"
                    onClick={() => setUpdateCategoryModalVisible(false)}
                >
                    取消
                </Button>,
                <Button 
                    key="ok" 
                    type="primary"
                    className="bg-[#D6A7A1] hover:bg-[#E8D6D0] text-white rounded-md transition-all text-sm px-3 py-1.5"
                    onClick={() => {
                        updateCategoryForm.validateFields().then((values) => {
                            handleUpdateCategory(values);
                        }).catch((errorInfo) => {
                            console.log('表单验证失败:', errorInfo);
                        });
                    }}
                >
                    更新
                </Button>,
            ]}
        >
            <div className="p-4 bg-white rounded-lg shadow-sm">
                <Form form={updateCategoryForm} layout="vertical">
                    <Form.Item
                        label={<span className={`${styles.text} font-medium text-gray-700`}>分区ID</span>}
                        name="id"
                        initialValue={selectedCategory?.id}
                        disabled
                    >
                        <Input className="rounded-md border-gray-300 bg-gray-100 cursor-not-allowed" disabled />
                    </Form.Item>
                    <Form.Item
                        label={<span className={`${styles.text} font-medium text-gray-700`}>分区名称</span>}
                        name="name"
                        rules={[{ required: true, message: '请输入分区名称' }]}
                    >
                        <Input className="rounded-md border-gray-300 focus:border-[#D6A7A1] focus:ring focus:ring-[#D6A7A1]/20 transition-all" />
                    </Form.Item>
                    <Form.Item
                        label={<span className={`${styles.text} font-medium text-gray-700`}>分区描述</span>}
                        name="description"
                    >
                        <Input className="rounded-md border-gray-300 focus:border-[#D6A7A1] focus:ring focus:ring-[#D6A7A1]/20 transition-all" />
                    </Form.Item>
                </Form>
            </div>
        </Modal>
    </div> 
  );
}